import { useSetState } from 'ahooks';
import { Alert, Button, Input, message, Select } from 'antd';
import { useTranslation } from 'react-i18next';

import { AllowedMethod } from '@/utils/request';

const DOS = () => {
  const { t } = useTranslation();

  const [target, setTarget] = useSetState<{
    method: AllowedMethod;
    url: string;
  }>({
    method: 'GET',
    url: '/test',
  });
  const { method, url } = target;
  const [messageApi, messageCtx] = message.useMessage();
  const [accessCount, setAccessCount] = useSetState<any>({
    GET: {},
    POST: {},
    PUT: {},
    PATCH: {},
    DELETE: {},
  });

  const handleClick = () => {
    if (url.length === 0) {
      messageApi.info({ content: '格式错误' });
    }
    let isDOS = false;
    let DOSUrl: string[] = [];
    // await request(method, url);  // 模拟发送请求
    setAccessCount({
      ...accessCount,
      [method]: {
        ...accessCount[method],
        [url]: accessCount?.[method]?.[url] ? accessCount[method][url] + 1 : 1,
      },
    });
    Object.keys(accessCount).forEach(m => {
      Object.keys(accessCount[m]).forEach(u => {
        if (accessCount[m][u] >= 5) {
          isDOS = true;
          DOSUrl.push(`${m} ${u}`);
        }
      });
    });
    if (isDOS) {
      messageApi.info({ content: `对 | ${DOSUrl.join(' | ')}  | 构成DOS攻击` });
    } else {
      messageApi.info({ content: '多请求几次' });
    }
  };

  return (
    <>
      <Alert showIcon className="mb-4" type="warning" message={t('dosAdvice')} />
      <Input.Group compact>
        {messageCtx}
        <Select
          value={method}
          options={[
            { value: 'GET', label: 'GET' },
            { value: 'POST', label: 'POST' },
            { value: 'PUT', label: 'PUT' },
            { value: 'PATCH', label: 'PATCH' },
            { value: 'DELETE', label: 'DELETE' },
          ]}
          onSelect={(value: AllowedMethod) => setTarget({ method: value })}
        />
        <Input
          required
          value={url}
          style={{ width: '200px', maxWidth: '100%' }}
          placeholder="URL..."
          onChange={e => setTarget({ url: e.target.value })}
        />
        <Button onClick={handleClick}>{t('confirm')}</Button>
      </Input.Group>
    </>
  );
};

export default DOS;
